import time
import multiprocessing
import subprocess
import psutil
from threading import Thread

import gradio as gr



def print_gpu():
    # 打印 GPU 信息, 需要系统有 ixsmi 命令
    try:
        result = subprocess.run(['ixsmi'], capture_output=True, text=True)
        print('ixsmi Output:', result.stdout)
    except Exception as e:
        print('没有 ixsmi 命令')


def print_cpu():
    # 打印CPU信息
    print("CPU信息:")
    cpu_count = psutil.cpu_count(logical=False)  # 获取物理CPU数量
    print(f"物理CPU数量: {cpu_count}")
    cpu_count_logical = psutil.cpu_count()  # 获取逻辑CPU数量
    print(f"逻辑CPU数量: {cpu_count_logical}")
    cpu_freq = psutil.cpu_freq()  # 获取CPU频率
    print(f"CPU频率: {cpu_freq.current} MHz")

    # 打印内存信息
    print("\n内存信息:")
    memory = psutil.virtual_memory()
    print(f"总内存: {memory.total / (1024 ** 3):.2f} GB")
    print(f"可用内存: {memory.available / (1024 ** 3):.2f} GB")
    print(f"已使用内存: {memory.used / (1024 ** 3):.2f} GB")
    print(f"内存使用率: {memory.percent}%")

    # 打印当前CPU使用率
    print("\n当前CPU使用率:")
    cpu_usage = psutil.cpu_percent(interval=1)  # interval参数表示间隔时间，单位为秒
    print(f"CPU使用率: {cpu_usage}%")

    # 打印当前内存使用率
    print("\n当前内存使用率:")
    memory_usage = memory.percent
    print(f"内存使用率: {memory_usage}%")


def print_gpu_process(event, stop_event):
    while not stop_event.is_set():  # 检查事件是否被设置
        if event.is_set():
            print_gpu()
            print_cpu()
        time.sleep(2)
    print("子进程结束")


def start_print_gpu_process(event, stop_event):
    # 创建一个新的进程
    process = multiprocessing.Process(target=print_gpu_process, args=(event, stop_event,))
    # 启动子进程
    process.start()
    print("启动子进程")
    return process




print_event = multiprocessing.Event()
# 创建一个事件，用于通知子进程何时停止
stop_event = multiprocessing.Event()



def greet(name, intensity):
    return "Hello, " + name + "!" * int(intensity)







def main1():
    print_event.set()
    # 启动子进程
    print_process = start_print_gpu_process(print_event, stop_event)
    
    demo = gr.Interface(
        fn=greet,
        inputs=["text", "slider"],
        outputs=["text"],
    )

    demo.launch()


# 使用 gradio 显示 cpu, gpu, 内存, 显存的使用率, 实时显示



# 定义一个全局变量来存储资源使用情况
system_info = {
    'CPU Usage': 0,
    'Memory Usage': 0,
    'GPU Usage': []
}


def get_system_info():
    global system_info

    # 更新CPU使用率
    system_info['CPU Usage'] = psutil.cpu_percent(interval=None)

    # 更新内存使用情况
    memory = psutil.virtual_memory()
    system_info['Memory Usage'] = memory.percent

    # 更新GPU使用情况
    gpus = []
    try:
        import GPUtil
        gpus = GPUtil.getGPUs()
        system_info['GPU Usage'] = [gpu.load * 100 for gpu in gpus]
    except ImportError:
        system_info['GPU Usage'] = [0]  # 如果没有GPU或GPUtil未安装，则GPU使用率为0

    return system_info


def update_system_info():
    while True:
        system_info = get_system_info()
        time.sleep(1)


def main2():
    # 创建一个线程来周期性地更新系统信息
    update_thread = Thread(target=update_system_info)
    update_thread.start()



    # 定义Gradio界面
    # iface = gr.Interface(
    #     # fn=lambda: system_info,  # 使用lambda函数来获取最新的系统信息
    #     fn=greet,
    #     inputs="null",  # 没有输入
    #     outputs=gr.Textbox(lines=10, label="System Information"),
    #     title="System Monitor",
    #     description="Monitor CPU, Memory, and GPU usage in real-time."
    # )

    iface = gr.Interface(
        fn=lambda a,b : system_info,
        inputs=None,  # 没有输入
        outputs=["text"],
        title="System Monitor",
        description="Monitor CPU, Memory, and GPU usage in real-time."
    )

    # 运行界面
    iface.launch()


def get_time():
    return time.ctime()


def main3():
    with gr.Blocks() as demo:
        # 创建一个简单的文本输入和显示当前时间的组件
        text_input = gr.Textbox(show_label=False)
        current_time = gr.Textbox(show_label=False)
        current_time.value = get_time()

        # 定时更新时间的 JavaScript 代码
        js_code = """
        setInterval(() => {
            const timeElement = document.getElementById("current_time");
            timeElement.value = new Date().toTimeString().split(' ')[0];
        }, 1000);
        """

        # 将 JavaScript 代码添加到界面中
        demo.js = js_code

    demo.launch()


if __name__ == "__main__":
    print('')
    main3()